const selectText = '请选择'
const tipSelectComs = ['Cascader', 'Select', 'AekCascader', 'AekSelect', 'AekTreeSelect', 'TreeSelect'] // 'DatePicker', 'RangePicker',
const inputText = '请输入'
const tipInputTextComs = [
  'Input',
  'InputSearch',
  'InputNumber',
  'InputPassword',
  'TextArea',
  'AekTextArea',
  'AekInputNumber',
]

/**
 * @param {import("./index").FormDataProps} itemObj
 * @param {boolean} allView
 * @returns
 */
const transformFromItem = (itemObj, allView) => {
  const item = { ...itemObj }
  if (allView || item.view) {
    return item
  }
  if (Array.isArray(item.component)) {
    item.component = item.component.map(_item => transformFromItem(_item, allView))
    return item
  }
  if (!item.component?.props?.placeholder) {
    const tipSelect = item.component.name !== 'RangePicker' && tipSelectComs.includes(item.component.name)
    if (tipSelect) {
      item.component.props = item.component.props || {}
      item.component.props.placeholder = `${selectText}${item.label || ''}`
    }
    const tipInput = tipInputTextComs.includes(item.component.name)
    if (tipInput) {
      item.component.props = item.component.props || {}
      item.component.props.placeholder = `${inputText}${item.label || ''}`
    }
  }
  if (item.formItemProps?.rules && typeof item.component?.name === 'string') {
    const rule = item.formItemProps?.rules.find(({ required }) => required === true)
    if (rule && !rule.message) {
      const tipSelect = tipSelectComs.includes(item.component.name)
      if (tipSelect) {
        rule.message = `${selectText}${item.label || ''}`
      }
      const tipInput = tipInputTextComs.includes(item.component.name)
      if (tipInput) {
        rule.message = `${inputText}${item.label || ''}`
      }
    }
  }
  if (item.component) {
    const name = typeof item.component === 'string' ? item.component : item.component.name
    if (name) {
      const { props = {} } = item.component
      const { options } = props
      if (['Select'].includes(name) && options) {
        item.type = 'select'
      } else if (['Input', 'AutoComplete'].includes(name)) {
        item.type = 'input'
      } else if (['UploadButton', 'PhotoWall'].includes(name)) {
        item.type = 'img'
      }
    }
    switch (item.type) {
      case 'input':
        if (Array.isArray(item.rules)) {
          item.rules.some(itm => {
            if (itm.required && !itm.transform) {
              itm.transform = value => (value || '').trim()
              return true
            }
            return false
          })
        }
        break
      case 'select':
        item.component = {
          name: 'Select',
          props: {
            allowClear: true,
            defaultActiveFirstOption: false,
            ...item.component.props,
          },
        }
        break
      default:
        break
    }
  }
  return item
}

export { transformFromItem }
